import { Button } from "antd"
import DirectoryTree from "antd/es/tree/DirectoryTree"
import { ReactNode, useRef, useState } from "react"
import { Loading , SourceBtn } from "../Components"


const Editor: React.FC = () => {
  const [list, setList] = useState<any[]>([])
  const [fileInner, setFileInner] = useState<ReactNode[]>([])
  const [loading, setLoading] = useState(false)
  const floderData = useRef(null)

  const selectFolder = async () => {
    setLoading(true)
    try {
      const folderHandle = await (window as any).showDirectoryPicker()
      const folderList = await processHandle(folderHandle)
      const treeData = reactTreeData(folderList?.children ?? [])
      floderData.current = folderList?.children
      setList(treeData)

    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false)
    }
  }

  const reactTreeData = (data: any, level?: number[]) => {
    return data.map((item: any, idx: number) => ({
      ...item,
      key: [...(level ?? []), idx],
      title: item.name,
      isLeaf: item.kind === 'file',
      children: reactTreeData(item.children ?? [], [...(level ?? []), idx])
    }))
  }
// 
  const processHandle = async (handle: any) => {
    if (handle.kind === 'file') {
      return handle
    } else {
      handle.children = []
      const iter = await handle.entries() // 得到当前文件夹的迭代器, 文件因为没有子元素所以无需迭代
      for await (const item of iter) {
        handle.children.push(await processHandle(item[1]))
      }
      return handle
    }
  }

  const getFile = (list: any, level: number[]): any => {
    const index = level.shift() as number
    if (level.length > 0) {
      return getFile(list[index].children, level)
    } else {
      return list[index]
    }
  }

  const clickFile = async (data: any) => {
    const fileHandle = getFile(floderData.current, data.shift())
    const file = await fileHandle.getFile()
    const render = new FileReader()
    render.onload = (e) => {
      console.log(e.target)
      if (typeof e.target?.result === 'string') {
        const doms: ReactNode[] = []
        const arr = e.target?.result?.split('\n')
        console.log(arr)
        arr.forEach(item => {
          doms.push(
            <>
              <div>{item.replace(/\r/g, '\xa0')}</div>
              <br />
            </>
          )
        })
        setFileInner(doms)
      }
    }
    render.readAsText(file, 'utf-8')

  }


  return (

    <div style={{ display: 'flex' }}>
      <div style={{ width: 400, height: '100vh', border: '  1px solid #666' ,boxShadow:' 0 5px 10px rgba(0, 0, 0, 0.1)' }}>
        <div style={{ display: 'block', margin: 30 }}>
          <SourceBtn  type='shiny'  onClick={selectFolder} >选择文件夹</SourceBtn>
          <SourceBtn  type='shinydarken'  onClick={selectFolder} >选择文件夹</SourceBtn>
          <DirectoryTree
            multiple
            defaultExpandAll
            onSelect={clickFile}
            treeData={list}
          />
        </div>
      </div>
      <div style={{ width: '100%', border: 'solid 1px green', height: '100vh', overflow: 'auto', padding: 30 }}>
        {fileInner}
      </div>
      <div
        style={{
          display: loading ? undefined : 'none',
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100vw',
          height: '100vh',
          background: 'rgba(102, 102, 102, 0.5)'
        }}>
        <div style={{ display: 'inline-block', margin: '200px 0 0 50%', transform: 'translateX(-50%)'}}>
          <Loading />
          <div style={{ fontSize: 24, textAlign: 'center', marginTop: 50 }}>加载中...</div>
        </div>
      </div>
    </div>
  )
}

export default Editor